//
// GPSMapEdit
// (c) Konstantin Galichsky (kg@geopainting.com), 2002-2005
//
// Dialog for editing text.
//

# include "StdAfx.h"
# include "Resource.h"
# include "EditText.h"
# include "Globals.h"

struct edit_data_t {
	string_t * pText;
	const char * strTitle;
};

static
INT_PTR CALLBACK _EditProc (HWND _hWnd, UINT _uMsg, WPARAM _wParam, LPARAM _lParam) {
	switch (_uMsg) {
		case WM_INITDIALOG: {
			edit_data_t * const pData = reinterpret_cast<edit_data_t *> (_lParam);
			::SetWindowLong (_hWnd, GWL_USERDATA, _lParam);

			::SetWindowText (_hWnd, pData->strTitle);

			const HWND hText = ::GetDlgItem (_hWnd, IDC_TEXT);

			assert (pData->pText != NULL);
			::SendMessage (hText, EM_LIMITTEXT, -1/*pData->pText->size ()*2 + 1*/, 0);
			::SetWindowText (hText, pData->pText->c_str ());

			::EnableWindow (::GetDlgItem (_hWnd, IDOK), FALSE);

			return TRUE;
		}

		case WM_COMMAND: {
			switch (LOWORD (_wParam)) {
				case IDC_TEXT: {
					if (HIWORD (_wParam) == EN_CHANGE)
						::EnableWindow (::GetDlgItem (_hWnd, IDOK), TRUE);
					return TRUE;
				}

				case IDOK: {
					const HWND hText = ::GetDlgItem (_hWnd, IDC_TEXT);

					// Get text.
					const size_t cLen = ::GetWindowTextLength (hText);
					char * const strText = reinterpret_cast<char *> (alloca (cLen + 1));
					::GetWindowText (hText, strText, cLen + 1);

					// Save the text.
					edit_data_t * const pData = reinterpret_cast<edit_data_t *> (::GetWindowLong (_hWnd, GWL_USERDATA));
					assert (pData->pText != NULL);
					pData->pText->assign (strText);

					::EndDialog (_hWnd, 0);

					return TRUE;
				}

				case IDCANCEL:
					::EndDialog (_hWnd, 1);
					return TRUE;
			}
		}
	}

	return FALSE;
}

bool EditText (HWND _hWnd, string_t & _str, const char * _strTitle, bool _bMultiline) {
	edit_data_t data = {& _str, _strTitle};
	return DlgBox (
		_bMultiline ? IDD_EDIT_TEXT_MULTI : IDD_EDIT_TEXT_SINGLE,
		_hWnd, _EditProc, reinterpret_cast<LPARAM> (& data)
	) == 0;
}
